﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace DATN.mds.ActionPlanManagement
{
    public partial class IndexAP : System.Web.UI.Page
    {
        
        SqlConnection cnn;
        int id;
        string d1 = "";
        string d2 = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Us_Id"] != null)
            {
                if (!IsPostBack)
                {
                    id = Convert.ToInt32(Session["Opp_Id"].ToString());
                    Load_data(id,d1,d2);
                    load_datadrop();
                    Idex_OppDdl.Items.FindByValue(Session["Opp_Id"].ToString()).Selected = true;   
                }
            }
            else
            {
                Response.Redirect("../Account/Login.aspx");
            }
        }

        
        protected void Load_data(int id,string date1, string date2)
        {
            try
            {
                cnn = new SqlConnection();
                cnn.ConnectionString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn.Open();

                string sqlA = "";
                if (date1 == "" && date2 == "")
                {
                    sqlA = "Select * From ActionPlan Where Opp_Id = " + id;
                }
                else
                {
                    sqlA = "Select * From ActionPlan Where Time between '" + date1.ToString() + "' And '" +
                        "" + date2.ToString() + "' And Opp_Id = " + id;
                }
                //lb_IdCheckBox.Text = sqlA.ToString();
                SqlDataAdapter da = new SqlDataAdapter(sqlA, cnn);
                DataSet ds = new DataSet();
                da.Fill(ds, "ActionPlan");

                Idex_Ac.DataSource = ds.Tables["ActionPlan"];
                Idex_Ac.DataBind();

                //ds.Dispose();
                //da.Dispose();
                cnn.Close();
            }
            catch (Exception ex)
            {
                Response.Write("Lỗi: " + ex);
            }
            finally
            {
                cnn.Close();
            }
        }

        protected void load_datadrop() 
        {
            try
            {
                cnn = new SqlConnection();
                cnn.ConnectionString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn.Open();

                string sqlA = "Select * From Opportunities Where Us_Id = " + Convert.ToInt32(Session["Us_Id"].ToString());
                SqlDataAdapter da = new SqlDataAdapter(sqlA, cnn);
                DataSet ds = new DataSet();
                da.Fill(ds, "Opportunities");

                Idex_OppDdl.DataSource = ds;
                Idex_OppDdl.DataTextField = ds.Tables["Opportunities"].Columns["Name"].ToString();
                Idex_OppDdl.DataValueField = ds.Tables["Opportunities"].Columns["Opp_Id"].ToString();
                Idex_OppDdl.DataBind();

                //Label1.Text = ds.Tables["Opp"].Rows[0].ItemArray[0].ToString();
                //DropDownList1.Items.FindByValue(ds.Tables["ActionPlan"].Rows[0].ItemArray[0].ToString()).Selected = true;

                //ds1.Dispose();
                //da1.Dispose();
                ds.Dispose();
                da.Dispose();
                cnn.Close();
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex);
            }
            finally
            {
                cnn.Close();
            }
            
        
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            
            if (e.CommandName == "Delete")
            {
                // get the categoryID of the clicked row
                try
                {
                    int Ac_Id = Convert.ToInt32(e.CommandArgument);
                    // Create New Session And Redirect to delete page
                    Session["Ac_Id"] = Ac_Id.ToString();
                    //Response.Redirect("/mds.OpportunityManagement/DeleteOM.aspx");
                }
                catch (Exception ex)
                {
                    Response.Write(ex);
                }
            }
            if (e.CommandName == "Edit")
            {
                // get the categoryID of the clicked row
                try
                {
                    int Opp_Id = Convert.ToInt32(e.CommandArgument);
                    // Create New Session And Redirect to delete page
                    Session["Ac_Id"] = Opp_Id.ToString();
                    Page.Response.Redirect("~/mds.ActionPlanManagement/EditAP.aspx");
                }
                catch (Exception ex)
                {
                    Response.Write(ex);
                }
            }
            
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                SqlConnection cnn = new SqlConnection();
                cnn.ConnectionString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                string ac = "Delete From ActionPlan Where Ac_Id =" + Convert.ToInt32(Session["Ac_Id"].ToString());

                SqlCommand cmd = cnn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = ac;

                cnn.Open();
                cmd.ExecuteNonQuery();
                cnn.Close();
                id = Convert.ToInt32(Session["Opp_Id"].ToString());
                Load_data(id,d1,d2);
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex);
            }
        }

        protected void bt_Creat_Click(object sender, EventArgs e)
        {
            Page.Response.Redirect("~/mds.ActionPlanManagement/CreateNewAP.aspx");
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
                l.Attributes.Add("onclick", "javascript:return " +
                "confirm('Bạn muốn sửa nội dung trong cột này!')");

                LinkButton l2 = (LinkButton)e.Row.FindControl("LinkButton2");
                l2.Attributes.Add("onclick", "javascript:return " +
                "confirm('Bạn muốn xóa nội dung trong cột này!')");
            }
            if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
            {
                CheckBox chkBxSelect = (CheckBox)e.Row.Cells[0].FindControl("chkBxSelect");
                CheckBox chkBxHeader = (CheckBox)this.Idex_Ac.HeaderRow.FindControl("chkBxHeader");
                HiddenField hdnFldId = (HiddenField)e.Row.Cells[0].FindControl("hdnFldId");

                chkBxSelect.Attributes["onclick"] = string.Format("javascript:ChildClick(this,document.getElementById('{0}'),'{1}');", chkBxHeader.ClientID, hdnFldId.Value.Trim());
            }
        }

        protected void btnCheckBox_Click(object sender, EventArgs e)
        {
            //Get Ids
            string[] IDs = hdnFldSelectedValues.Value.Trim().Split('|');
            
            if (IDs.Length > 0)
            {
                for (int i = 0; i < IDs.Length; i++)
                {
                    lb_IdCheckBox.Text += IDs[i] + ";";
                    int id = int.Parse(IDs[i]);
                    DeleteMany(id);
                }
            }
            else
            {
                lb_IdCheckBox.Text = "Bạn Chưa chọn Khách Hàng Nào cả!";
            }
            Load_data(Convert.ToInt32(Session["Opp_Id"].ToString()),d1,d2);
        }

        protected void DeleteMany(int id)
        {
            
            SqlConnection cnn = new SqlConnection();
            cnn.ConnectionString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
            //int xid = id;
            string com = "Delete From ActionPlan Where Ac_Id = " + id;

            SqlCommand cmd = cnn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = com;
            
            cnn.Open();
            cmd.ExecuteNonQuery();
            cnn.Close();
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            id = Convert.ToInt32(Idex_OppDdl.SelectedValue);
            Session["Opp_Id"] = id.ToString();
            Load_data(id,d1,d2);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Page.Response.Redirect("~/mds.ActionPlanManagement/SearchAP.aspx");

        }

        protected void btt_timkiem_Ac_Click(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                DateTime dd1 = DateTime.Parse(idex_txtDateFrom.Text);
                d1 = dd1.ToString("MM/dd/yyyy");

                DateTime dd2 = DateTime.Parse(idex_txtDateTo.Text);
                d2 = dd2.ToString("MM/dd/yyyy");

                id = Convert.ToInt32(Idex_OppDdl.SelectedValue);
                Session["Opp_Id"] = id.ToString();

                Load_data(id, d1, d2);
                //lb_IdCheckBox.Text=d1.ToString()+ d2.ToString();
            }
        }

        protected void Idex_Ac_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            Idex_Ac.PageIndex = e.NewPageIndex;

            DateTime dd1 = DateTime.Parse(idex_txtDateFrom.Text);
            d1 = dd1.ToString("MM/dd/yyyy");

            DateTime dd2 = DateTime.Parse(idex_txtDateTo.Text);
            d2 = dd2.ToString("MM/dd/yyyy");

            id = Convert.ToInt32(Idex_OppDdl.SelectedValue);
            Session["Opp_Id"] = id.ToString();

            Load_data(id, d1, d2);
        }

    }
}